package com.leetcode.hash;

import java.util.HashMap;

/**
 * @author Dennis Li
 * @date 2020/7/19 20:13
 */
public class TwoSum_1 {

    public int[] twoSum(int[] nums, int target) {
        if(nums.length < 2) return new int[0];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(!map.containsKey(nums[i]))
                map.put(nums[i], i);
            else if(nums[i] << 1 == target){
                // 如果已经有此数，那么判断它的二倍是否恰好是target
                return new int[]{map.get(nums[i]), i};
            }
        }
        for (int i = 0; i < nums.length; i++) {
            // 在前面已经排除了为二倍的情况
            if (target >> 1 != nums[i] && map.containsKey(target - nums[i])){
                return new int[]{i, map.get(target - nums[i])};
            }
        }
        return new int[0];
    }

}
